<?php

namespace app\common\model;

use app\common\controller\Helper;
use think\Db;
use think\Model;
use app\common\service\Order;

class OauthOrder extends Model
{
    use Helper;

    protected $table = 'oauth_order';

    
    const TYPE_DELETE = 0;
    const TYPE_SELF = 1;
    const TYPE_SHARE = 2;
    const TYPE_ADMIN = 3;
    const PAY_ALIPAY = 1;
    const PAY_WECHAT = 2;
    const PAY_APPLE = 3;

    public static function attributes($attribute, $key = null)
    {
        $list = [
            'type' => [
                self::TYPE_DELETE => '取消支付',
                self::TYPE_SELF => '自主',
                self::TYPE_SHARE => '分享',
                self::TYPE_ADMIN => '线下',
            ],
            'pay_type' => [
                self::PAY_ALIPAY => '支付宝',
                self::PAY_WECHAT => '微信',
                self::PAY_APPLE => '苹果内购'
            ]
        ];
        return self::attributeReturn($list, $attribute, $key);
    }

    /**
     * 获取订单号
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOrderSn()
    {
        $orderSn = Order::orderSn();
        $next = true;
        while ($next) {
            $model = self::getOneByOrder($orderSn);
            if (empty($model)) {
                $next = false;
            } else {
                $orderSn = Order::orderSn();
            }
        }
        return $orderSn;
    }

    /**
     * 根据订单号查找订单
     * @param $orderSn
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOneByOrder($orderSn)
    {
        return static::field('id,pay_status,oauth_id')
            ->where(['order_sn' => $orderSn])
            ->find();
    }

    /**
     * 支付结果通知回调
     * @param string $openid 当前支付用户openid
     * @param string $orderSn 订单号
     * @param string $payMoney 支付金额
     * @param string $attach
     * @param string $remark
     * @param string $msg 返回信息
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function orderPaid($openid, $orderSn, $payMoney, $attach, $remark, &$msg,$auth)
    {
        $attach = '<xml><appid><![CDATA[wxd65d8e8fa81ed7cc]]></appid>
<attach><![CDATA[{"cs":"20","rm":0,"cn":0,"code":123456,"key":"VzHsZsDICo","kf":"15"}]]></attach>
<bank_type><![CDATA[CCB_DEBIT]]></bank_type>
<cash_fee><![CDATA[120000]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[N]]></is_subscribe>
<mch_id><![CDATA[1483825742]]></mch_id>
<nonce_str><![CDATA[hw5vwbl0ry6y7qkfkfu1xls8jkmj63uw]]></nonce_str>
<openid><![CDATA[osg7fwDvKKzTnbzvISq4L-LGuUrk]]></openid>
<out_trade_no><![CDATA[20200601114454961588]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[0679E493E407037E577C93A01692AF17]]></sign>
<time_end><![CDATA[20200601114500]]></time_end>
<total_fee>120000</total_fee>
<trade_type><![CDATA[APP]]></trade_type>
<transaction_id><![CDATA[4200000541202006012014908877]]></transaction_id>
</xml>';
        $postObj = simplexml_load_string($attach, 'SimpleXMLElement', LIBXML_NOCDATA);
        $xml= json_encode($postObj);
        $attach=json_decode($xml,true);
//        $attach = json_decode($attach, true);

        $attach['cs'] = 20;
        $attach['rm'] = 0;
        $attach['cn'] = 0;
        $attach['code'] = 123456;
        $attach['key'] = 'VzHsZsDICo';
        $attach['kf'] = 15;


        if (!isset($attach['cs']) || !isset($attach['rm']) || !isset($attach['cn'])
            || !isset($attach['key']) || !isset($attach['kf'])
        ) {
            $msg = '参数错误';
            return false;
        }

        // 购买的班级ids
        $classIds = $attach['cs'];
        // 积分抵扣的金额
        $reduceMoney = $attach['rm'];
        // 使用的优惠券id
        $couponId = $attach['cn'];
        // 分享出去的键
        $shareKey = $attach['key'];
        // 客服id
        $customerId = $attach['kf'];
        $code = $attach['code'];
        // 订单类型，后台添加的有返回$attach['t']
        $type = isset($attach['t']) ? $attach['t'] : 0;
        // 支付方式，后台添加可选择支付方式，否则默认微信支付
        $payType = isset($attach['pt']) ? $attach['pt'] : self::PAY_WECHAT;

        $classIdsArr = explode(',', $classIds);
        $classIdsArr = array_unique(array_filter($classIdsArr));
        if (!is_array($classIdsArr) || count($classIdsArr) <= 0) {
            $msg = '未选择班级';
            return false;
        }

        // 查找订单
        $order = OauthOrder::getOneByOrder($orderSn);

        if ($order && $order['pay_status']==1) {

            $msg = '订单号已购买';
            return false;
        }

        // 查找对应的用户
        $oauth = empty($openid) ? $auth : Oauth::getByOpenId($openid);
        if (empty($oauth)) {
            $msg = '用户不存在';
            return false;
        }

        // 判断课程有没购买过
//        $has = OauthOrderClass::hasBuy($oauth['id'], $classIdsArr);
//        if ($has) {
//            $msg = '存在已经购买过的班级';
//            return false;
//        }

        // 查找班级
        $class = LangClass::getClasses($classIdsArr);

        if (empty($class)) {
            $msg = '班级不存在';
            return false;
        }

        $money = 0;
        $reIntegral = 0;
        if ($reduceMoney > 0) {
            // 可兑换的金额
            $canReduce = Config::getReduceMoney($oauth['integral']);
            if ($reduceMoney != $canReduce) {
                $msg = '积分可抵扣金额错误';
                return false;
            }

            $money += $canReduce;

            // 获取抵扣的积分
            $config = Config::getOne('deduction');
            $reIntegral = ($config['money'] != 0) ? ($config['integral'] / $config['money'] * $canReduce) : 0;
        }

        // 查找优惠券
        $couponMoney = 0;
        $couponName = '';
        if ($couponId > 0) {
            $coupon = Coupon::getOne($couponId);
            if (empty($coupon)) {
                $msg = '优惠券不存在或者已过期';
                return false;
            }

            // 判断优惠券是否已经使用
            $used = CouponUsed::getOne($oauth['id'], $couponId);
            if ($used) {
                $msg = '该优惠券已经使用过，不能重复使用';
                return false;
            }

            $couponMoney = $coupon['money'];
            $money += $couponMoney;
            $couponName = $coupon['name'];
        }

        // 处理班级数据
        $classData = LangClass::classData($class);

        $sumMoney = $classData['sum'];

        // 实际金额 = 班级金额 - 积分抵扣金额 - 优惠券金额
        $realMoney = $sumMoney - $money;

        // 一次性购买多个班级，可享受优惠价格，每个班级优惠100元
        $classNum = count($class);
        if ($classNum > 1) {
            $after = $realMoney - ($classNum * 100);
            $realMoney = $after > 0 ? $after : 0;
        }

//        if ($realMoney <= 0) {
//            $msg = '支付金额非法，实际支付金额小于0';
//            return false;
//            $realMoney = 0;
//        }

        // 不是后台添加的，需要验证支付金额
//        if ($type != self::TYPE_ADMIN) {
//            $payMoney = round($payMoney, 2);
//            $realMoney = round($realMoney, 2);
//            if ($payMoney != $realMoney) {
//                $msg = '支付金额错误';
//                return false;
//            }
//        }

        // 启动事务
        Db::startTrans();
        try {
            $shareOauth = [];
            $commission = 0;
            $salesCommission = 0;
            $agentCommission = 0;
            $total = 0;
            // 不是自己分享给自己
            if ($shareKey && $oauth['share_key'] != $shareKey) {
                $shareOauth = Oauth::getOneByKey($shareKey);
                if ($shareOauth) {
                    // 获取佣金配置
                    $commissionConfig = Config::getOne('commission');
                    if ($commissionConfig > 0) {
                        $commission = round($payMoney * $commissionConfig / 100, 2);
                    }
                }
            }

            //查看邀请码
            if (!empty($code)) {
                $codeOauth = Db::name('oauth')->where('code',$code)->find();
                if ($codeOauth['type'] == 2) {
                    //代理佣金
                    $salesCommissionConfig= Config::getOne('sales_commission');
                    if ($commissionConfig > 0) {
                        $salesCommission =  bcmul(1200,bcdiv($salesCommissionConfig,100,2),2);
                    }
                    //查找分享码拥有人
                    $codeOauth = Db::name('oauth')->where('code',$code)->find();
                    //查看是不是有没有上级 有的话 需要加上销售佣金
                    $agentId = $codeOauth['agent'] ? $codeOauth['agent'] :0;
                    if (!empty($agentId)) {
                        //销售佣金
                        $agentCommissionConfig = Config::getOne('agent_commission');
                        if ($agentCommissionConfig > 0) {
                            $agentCommission =  bcmul(1200,bcdiv($agentCommissionConfig,100,2),2);
                        }
                    }
                } else {
                    //销售佣金
                    $agentCommissionConfig = Config::getOne('agent_commission');
                    if ($agentCommissionConfig > 0) {
                        $agentCommission =  bcmul(1200,bcdiv($agentCommissionConfig,100,2),2);
                    }
                }
                //总的佣金
                $total  = bcadd($salesCommission,$agentCommission,2);
            }

            // 订单类型，1自主，2分享，3后台线下
            if ($type <= 0) {
                $type = !empty($shareOauth) ? self::TYPE_SHARE : self::TYPE_SELF;
            }
            //为空则取其他值
            $nickName = $oauth['nickname'];
            if(empty($nickName)){
                if(!empty($oauth['phone'])){
                    $nickName = $oauth['phone'];
                }else if(!empty($oauth['device_info'])){
                    $nickName = $oauth['device_info'];
                }
            }

            // 1. 添加订单记录
            $orderId = Db::name('oauth_order')->insertGetId([
                'order_sn' => $orderSn,
                'type' => $type,
                'oauth_id' => $oauth['id'],
                'oauth_nickname' => $nickName,
                'lang_id' => $classData['langId'],
                'money' => $sumMoney,
                'integral' => $reIntegral,
                'customer_id' => $customerId,
                'coupon_id' => $couponId,
                'coupon_name' => $couponName,
                'coupon' => $couponMoney,
                'pay_type' => $payType,
                'code' => $code,
                'pay_money' => $payMoney,
                'remark' => $remark,
                'share_uid' => !empty($shareOauth) ? $shareOauth['id'] : 0,
                'share_nickname' => !empty($shareOauth) ? $shareOauth['nickname'] : '',
                'share_commission' => $commission,
                'total_record' => $total,
                'create_time' => time(),
                'update_time' => time()
            ]);

//            // 2. 添加订单班级记录
            $orderClass = [];
            $commissionRecord = [];

            // 更新分享记录佣金信息
            if ($codeOauth) {
                $money = $codeOauth['type']==2 ? $salesCommission : $agentCommission;
                if ($codeOauth['type'] == 2 && !empty($codeOauth['agent']) ) {
                    Db::name('oauth_commission_record')->insertGetId([
                        'oauth_id' =>$oauth['id'],//购买人的ID
                        'agent_id' => $codeOauth['agent'],//分享邀请码的ID
                        'buy_nickname' => $oauth['nickname'],//购买人的昵称
                        'order_id' => $orderId,//订单号
                        'class_id' =>$classData['langId'],//课程ID
                        'code' => $codeOauth['code'],//分享码
                        'commission' => $agentCommission,//佣金
                        'create_time' => time(),
                        'type' =>1,
                    ]);
                    Db::name('oauth_money_log')->insertGetId([
                        'order_id' =>$orderId,//购买人的ID
                        'oauth_id' =>$codeOauth['agent'],//佣金所属人ID
                        'class_id' =>$classData['langId'],//课程ID
                        'money' => $agentCommission,//佣金
                        'remark' => '购买'.$money,
                        'create_time' => time(),
                        'type' =>1,
                    ]);
                    //增加销售余额
                    DB::name('oauth')->where('id',$codeOauth['agent'])->setInc('money',$agentCommission);
                }
                Db::name('oauth_commission_record')->insertGetId([
                    'oauth_id' =>$oauth['id'],//购买人的ID
                    'agent_id' => $codeOauth['id'],//分享邀请码的ID
                    'buy_nickname' => $oauth['nickname'],//购买人的昵称
                    'order_id' => $orderId,//订单号
                    'class_id' =>$classData['langId'],//课程ID
                    'code' => $codeOauth['code'],//分享码
                    'commission' => $salesCommission,//佣金
                    'create_time' => time(),
                    'type' =>2,
                ]);
                //增加佣金
                DB::name('oauth')->where('id',$codeOauth['id'])->setInc('money',$money);
            }


            foreach ($class as $cId => $value) {
                $orderClass[] = [
                    'order_id' => $orderId,
                    'oauth_id' => $oauth['id'],
                    'class_id' => $cId,
                    'class_type' => $value['typeId'],
                    'class_name' => $value['langName'] . $value['type'],
                    'money' => $value['money'],
                    'create_time' => time(),
                ];
                if ($codeOauth['type'] == 2 && !empty($codeOauth['agent']) ) {

                }
                $commissionRecord[] = [
                    'order_id' => $orderId,
                    'oauth_id' => $oauth['id'],
                    'class_id' => $cId,
                    'class_type' => $value['typeId'],
                    'class_name' => $value['langName'] . $value['type'],
                    'money' => $value['money'],
                    'create_time' => time(),
                ];
            }
            Db::name('oauth_order_class')->insertAll($orderClass);
//
            // 3. 扣除积分
            if ($reIntegral > 0) {
                Db::name('oauth')
                    ->where('id', $oauth['id'])
                    ->dec('integral', $reIntegral)
                    ->update();
                // 积分日志
                Db::name('oauth_integral')->insert([
                    'oauth_id' => $oauth['id'],
                    'type' => OauthIntegral::TYPE_BUY,
                    'before_num' => $oauth['integral'],
                    'after_num' => $oauth['integral'] - $reIntegral,
                    'order_id' => $orderId,
                    'create_time' => time()
                ]);
            }

            // 4. 添加已使用优惠券记录
            if ($couponId > 0) {
                Db::name('coupon_used')->insert([
                    'oauth_id' => $oauth['id'],
                    'coupon_id' => $couponId,
                    'order_id' => $orderId,
                    'order_sn' => $orderSn,
                    'create_time' => time()
                ]);
            }

            // 5. 分享加佣金（自己分享自己购买的排除）存在分享用户 并且 佣金大于0
            if ($shareOauth && $commission > 0) {
                // 佣金记录
                $commissionId = Db::name('oauth_commission')->insertGetId([
                    'oauth_id' => $shareOauth['id'],
                    'buy_uid' => $oauth['id'],
                    'buy_nickname' => $oauth['nickname'],
                    'order_id' => $orderId,
                    'commission' => $commission,
                    'create_time' => time(),
                ]);

                // 6. 提现（企业付款到个人账户）
                $transfers = OauthCommission::transfers($orderSn, $openid, $commission, '分享赚取佣金');
                if ($transfers['success'] === true) {
                    $paymentNo = $transfers['payment_no'];
                    $withdrawalStatus = OauthCommission::WITHDRAW_SUCCESS;
                } else {
                    $paymentNo = '';
                    $withdrawalStatus = OauthCommission::WITHDRAW_FAIL;
                }

                // 更新提现信息
                Db::name('oauth_commission')
                    ->where('id', $commissionId)
                    ->update([
                        'payment_no' => $paymentNo,
                        'withdrawal_status' => $withdrawalStatus,
                        'withdrawal_time' => time()
                    ]);
            }

            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            dump($e->getMessage());
            // 回滚事务
            Db::rollback();
            return false;
        }
    }
    
    
    /**
     * 下单入库
     * @param $orderSn
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function insertOrderSn($uid, $totalFee, $couponId, $outTradeNo,$customerId,$payType,$code){
        $orderId = Db::name('oauth_order')->insertGetId([
            'order_sn' => $outTradeNo,
            'oauth_id' => $uid,
            'money' => $totalFee,
            'customer_id' => $customerId,
            'coupon_id' => $couponId,
            'coupon_name' => $couponId,
            'pay_type' => $payType,
            'code' => $code,
            'total_record' => 0.00,
            'create_time' => time(),
            'update_time' => time()
        ]);
    }
    
    
    
    /**
     * 微信和支付app支付结果通知回调
     * @param string $openid 当前支付用户openid
     * @param string $orderSn 订单号
     * @param string $payMoney 支付金额
     * @param string $attach
     * @param string $remark
     * @param string $msg 返回信息
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function orderNotify($orderSn,$attach,$outer_trade_no,$payMoney)
    {
        $orderSn = '20200629142313665602';
        $payMoney =20900;
//        $attach = json_decode($attach, true);
        $attach = '<xml><appid><![CDATA[wxd65d8e8fa81ed7cc]]></appid>
<attach><![CDATA[{"cs":"20,21,22","rm":0,"cn":0,"code":123456,"key":"VzHsZsDICo","kf":"15"}]]></attach>
<bank_type><![CDATA[CCB_DEBIT]]></bank_type>
<cash_fee><![CDATA[120000]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[N]]></is_subscribe>
<mch_id><![CDATA[1483825742]]></mch_id>
<nonce_str><![CDATA[hw5vwbl0ry6y7qkfkfu1xls8jkmj63uw]]></nonce_str>
<openid><![CDATA[osg7fwDvKKzTnbzvISq4L-LGuUrk]]></openid>
<out_trade_no><![CDATA[20200601114454961588]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[0679E493E407037E577C93A01692AF17]]></sign>
<time_end><![CDATA[20200601114500]]></time_end>
<total_fee>120000</total_fee>
<trade_type><![CDATA[APP]]></trade_type>
<transaction_id><![CDATA[4200000541202006012014908877]]></transaction_id>
</xml>';
//        $attach = json_decode($attach, true);
        $postObj = simplexml_load_string($attach, 'SimpleXMLElement', LIBXML_NOCDATA);
        $xml= json_encode($postObj);
        $attach=json_decode($xml,true);

        self::debugLog('attach='.var_export($attach,true));
//        if (!isset($attach['cs']) || !isset($attach['rm']) || !isset($attach['cn'])
//            || !isset($attach['key']) || !isset($attach['kf'])
//        ) {
//            $msg = '参数错误';
//            return false;
//        }

        // 购买的班级ids
//        $classIds = $attach['cs'];
//        // 积分抵扣的金额
//        $reduceMoney = $attach['rm'];
//        // 使用的优惠券id
//        $couponId = $attach['cn'];
//        // 分享出去的键
//        $shareKey = $attach['key'];
//        // 客服id
//        $customerId = $attach['kf'];
//        $code = $attach['code'];
        $classIds = '20,21,22';
        $reduceMoney = 0;
        $couponId = 0;
        $code = 123456;
        $shareKey = 'VzHsZsDICo';
        $customerId['kf'] = 15;
        $attach['t'] = 1;
        // 订单类型，后台添加的有返回$attach['t']
        $type = isset($attach['t']) ? $attach['t'] : 0;
        // 支付方式，后台添加可选择支付方式，否则默认微信支付
        $payType = isset($attach['pt']) ? $attach['pt'] : self::PAY_WECHAT;
    
        $classIdsArr = explode(',', $classIds);
        $classIdsArr = array_unique(array_filter($classIdsArr));
//        self::debugLog('classIdsArr='.var_export($classIdsArr,true));
        if (!is_array($classIdsArr) || count($classIdsArr) <= 0) {
            $msg = '未选择班级';
            return false;
        }

        // 查找订单
        $order = OauthOrder::getOneByOrder($orderSn);
//        self::debugLog('order='.var_export($order,true));
//        if ($order && $order['pay_status']==1) {
//
//            $msg = '订单号已购买';
//            return false;
//        }

        // 查找对应的用户
        $oauth = Oauth::getOne($order['oauth_id']);

        if (empty($oauth)) {

            $msg = '用户不存在';
            return false;
        }

    
        // 判断课程有没购买过
        $has = OauthOrderClass::hasBuy($oauth['id'], $classIdsArr);
//        self::debugLog('has='.var_export($has,true));
//        if ($has) {
//            $msg = '存在已经购买过的班级';
//            return false;
//        }
        // 查找班级
        $class = LangClass::getClasses($classIdsArr);
//        if (empty($class)) {
//            $msg = '班级不存在';
//            return false;
//        }
        $money = 0;
        $reIntegral = 0;
        if ($reduceMoney > 0) {
            // 可兑换的金额
            $canReduce = Config::getReduceMoney($oauth['integral']);
            if ($reduceMoney != $canReduce) {
                $msg = '积分可抵扣金额错误';
                return false;
            }
    
            $money += $canReduce;
    
            // 获取抵扣的积分
            $config = Config::getOne('deduction');
            $reIntegral = ($config['money'] != 0) ? ($config['integral'] / $config['money'] * $canReduce) : 0;
        }
        // 查找优惠券
        $couponMoney = 0;
        $couponName = '';
        if ($couponId > 0) {
            $coupon = Coupon::getOne($couponId);
            if (empty($coupon)) {
                $msg = '优惠券不存在或者已过期';
                return false;
            }
    
            // 判断优惠券是否已经使用
            $used = CouponUsed::getOne($oauth['id'], $couponId);
            if ($used) {
                $msg = '该优惠券已经使用过，不能重复使用';
                return false;
            }
    
            $couponMoney = $coupon['money'];
            $money += $couponMoney;
            $couponName = $coupon['name'];
        }

        // 处理班级数据
        $classData = LangClass::classData($class);
        $sumMoney = $classData['sum'];

        // 实际金额 = 班级金额 - 积分抵扣金额 - 优惠券金额
        $realMoney = $sumMoney - $money;

        // 一次性购买多个班级，可享受优惠价格，每个班级优惠100元
        $classNum = count($class);
        if ($classNum > 1) {
            $after = $realMoney - ($classNum * 100);
            $realMoney = $after > 0 ? $after : 0;
        }
    
        if ($realMoney <= 0) {
            //            $msg = '支付金额非法，实际支付金额小于0';
            //            return false;
            $realMoney = 0;
        }

        // 不是后台添加的，需要验证支付金额
//        if ($type != self::TYPE_ADMIN) {
//            $payMoney = round($payMoney, 2);
//            $realMoney = round($realMoney, 2);
//            if ($payMoney != $realMoney) {
//                $msg = '支付金额错误';
//                return false;
//            }
//        }

        // 启动事务
        Db::startTrans();
        try {

            $shareOauth = [];
            $commission = 0;
            // 不是自己分享给自己
            if ($shareKey && $oauth['share_key'] != $shareKey) {
                $shareOauth = Oauth::getOneByKey($shareKey);
                if ($shareOauth) {
                    // 获取佣金配置
                    $commissionConfig = Config::getOne('commission');
                    if ($commissionConfig > 0) {
                        $commission = round($payMoney * $commissionConfig / 100, 2);
                    }
                }
            }
            // 订单类型，1自主，2分享，3后台线下
            if ($type <= 0) {
                $type = !empty($shareOauth) ? self::TYPE_SHARE : self::TYPE_SELF;
            }

            // 1. 更新订单记录表
            $orderId = $order['id'];
            $updataData = array();
            $updataData['out_trade_no']=$outer_trade_no;
            $updataData['type'] = $type;
            $updataData['oauth_nickname'] = $oauth['nickname'];
            $updataData['lang_id'] = $classData['langId'];
            $updataData['money'] = $sumMoney;
            $updataData['integral'] = $reIntegral;
//            $updataData['customer_id'] = $customerId;
            $updataData['coupon_id'] = $couponId;
            $updataData['coupon_name'] = $couponName? $couponName : '无';
            $updataData['coupon'] = $couponMoney;
            $updataData['pay_money'] = $payMoney;
            $updataData['pay_status'] = 1;
            $updataData['update_time'] = time();

            Db::name('oauth_order')->where('id', $orderId)->update($updataData);
//            self::debugLog('sql='.var_export(Db::name('oauth_order')->getLastSql(),true));




            //佣金
            //查看邀请码

//            dump($codeOauth);
//            dump($agentId);
//            dump($salesCommission);
//            dump($agentCommissionConfig);exit;
            // 2. 添加订单班级记录
            $orderClass = [];
            $commissionRecord = [];
            $moneyLog = [];
            $totalMoney = 0;
            $agentCommission = 0;
            $salesCommission = 0;
            $agentMoney = 0;
            $salesMoney = 0;


            foreach ($class as $cId => $value) {
                $orderClass[] = [
                    'order_id' => $orderId,
                    'oauth_id' => $oauth['id'],
                    'class_id' => $cId,
                    'class_type' => $value['typeId'],
                    'class_name' => $value['langName'] . $value['type'],
                    'money' => $value['money'],
                    'create_time' => time(),
                ];



                if (!empty($code)) {
                    $codeOauth = Db::name('oauth')->where('code',$code)->find();
                    if ($codeOauth['type'] == 2) {
                        //代理佣金
                        $salesCommissionConfig= Config::getOne('sales_commission');
                        if ($commissionConfig > 0) {
                            $salesCommission =  bcmul( $value['money'],bcdiv($salesCommissionConfig,100,2),2);
                        }
                        //查找分享码拥有人
//                    $codeOauth = Db::name('oauth')->where('code',$code)->find();
                        //查看是不是有没有上级 有的话 需要加上销售佣金
                        $agentId = $codeOauth['agent'] ? $codeOauth['agent'] :0;
                        if (!empty($agentId)) {
                            //销售佣金
                            $agentCommissionConfig = Config::getOne('agent_commission');
                            if ($agentCommissionConfig > 0) {
                                $agentCommission =  bcmul( $value['money'],bcdiv($agentCommissionConfig,100,2),2);
                            }
                        }
                    } else {
                        //销售佣金
                        $agentCommissionConfig = Config::getOne('agent_commission');
                        if ($agentCommissionConfig > 0) {
                            $agentCommission =  bcmul( $value['money'],bcdiv($agentCommissionConfig,100,2),2);
                        }
                    }

                }
                //代理
                if ($codeOauth['type'] == 2) {
//                    $salesMoney +=$salesCommission;

                    $moneyLog[] = [
                        'order_id' => $orderId,
                        'oauth_id' => $codeOauth['id'],
                        'class_id' => $cId,
                        'type' => 1,
                        'money' => $salesCommission,
                        'remark' =>  $value['langName'] . $value['type'],
                        'create_time' => time(),
                    ];
                    //钱包记录
                    $commissionRecord[] = [
                        'oauth_id' => $codeOauth['id'],
                        'buy_uid' => $oauth['id'],
                        'class_id' => $cId,
                        'buy_nickname' =>  $oauth['nickname'],
                        'order_id' => $orderId,
                        'code' => $code,
                        'commission' => $salesCommission,
                        'type' => 2,
                        'remark' =>  $value['langName'] . $value['type'],
                        'create_time' => time(),
                    ];
                    DB::name('oauth')->where('id',$codeOauth['id'])->setInc('money',$salesCommission);
                    //判断有没有销售
                    if (!empty($agentId)) {
                        $agentMoney += $agentCommission;
                        $moneyLog[] = [
                            'order_id' => $orderId,
                            'oauth_id' => $agentId,
                            'class_id' => $cId,
                            'type' => 1,
                            'money' => $agentCommission,
                            'remark' =>  $value['langName'] . $value['type'],
                            'create_time' => time(),
                        ];
                        //钱包记录
                        $commissionRecord[] = [
                            'oauth_id' => $agentId,
                            'buy_uid' => $oauth['id'],
                            'class_id' => $cId,
                            'buy_nickname' =>  $oauth['nickname'],
                            'order_id' => $orderId,
                            'code' => $code,
                            'commission' => $agentCommission,
                            'type' => 1,
                            'remark' =>  $value['langName'] . $value['type'],
                            'create_time' => time(),
                        ];
                        DB::name('oauth')->where('id',$agentId)->setInc('money',$agentCommission);
                    }
                } else {
                    $agentMoney += $agentCommission;
                    //销售佣金记录
                    $moneyLog[] = [
                        'order_id' => $orderId,
                        'oauth_id' => $codeOauth['id'],
                        'class_id' => $cId,
                        'type' => 1,
                        'money' => $agentCommission,
                        'remark' =>  $value['langName'] . $value['type'],
                        'create_time' => time(),
                    ];
                    //钱包记录
                    $commissionRecord[] = [
                            'oauth_id' => $codeOauth['id'],
                            'buy_uid' => $oauth['id'],
                            'class_id' => $cId,
                            'buy_nickname' =>  $oauth['nickname'],
                            'order_id' => $orderId,
                            'code' => $code,
                            'commission' => $agentCommission,
                            'type' => 1,
                            'remark' =>  $value['langName'] . $value['type'],
                            'create_time' => time(),
                    ];
                    DB::name('oauth')->where('id',$codeOauth['id'])->setInc('money',$agentCommission);
                }
                //总的佣金
                $totalMoney  += bcadd($salesCommission,$agentCommission,2);

            }

            //增加销售余额

            Db::name('oauth_money_log')->insertAll($moneyLog);
            Db::name('oauth_order_class')->insertAll($orderClass);
            Db::name('oauth_commission_record')->insertAll($commissionRecord);

            //订单总佣金

            Db::name('oauth_order')->where('id',$orderId)->update( ['total_record'=>$totalMoney]);
            // 3. 扣除积分
            if ($reIntegral > 0) {
                Db::name('oauth')
                ->where('id', $oauth['id'])
                ->dec('integral', $reIntegral)
                ->update();
                // 积分日志
                Db::name('oauth_integral')->insert([
                    'oauth_id' => $oauth['id'],
                    'type' => OauthIntegral::TYPE_BUY,
                    'before_num' => $oauth['integral'],
                    'after_num' => $oauth['integral'] - $reIntegral,
                    'order_id' => $orderId,
                    'create_time' => time()
                ]);
            }

            // 4. 添加已使用优惠券记录
            if ($couponId > 0) {
                Db::name('coupon_used')->insert([
                    'oauth_id' => $oauth['id'],
                    'coupon_id' => $couponId,
                    'order_id' => $orderId,
                    'order_sn' => $orderSn,
                    'create_time' => time()
                ]);
            }

//            // 5. 分享加佣金（自己分享自己购买的排除）存在分享用户 并且 佣金大于0
//            if ($shareOauth && $commission > 0) {
//                // 佣金记录
//                $commissionId = Db::name('oauth_commission')->insertGetId([
//                    'oauth_id' => $shareOauth['id'],
//                    'buy_uid' => $oauth['id'],
//                    'buy_nickname' => $oauth['nickname'],
//                    'order_id' => $orderId,
//                    'commission' => $commission,
//                    'create_time' => time(),
//                ]);
//
//                // 6. 提现（企业付款到个人账户）
//                $transfers = OauthCommission::transfers($orderSn, $openid, $commission, '分享赚取佣金');
//                if ($transfers['success'] === true) {
//                    $paymentNo = $transfers['payment_no'];
//                    $withdrawalStatus = OauthCommission::WITHDRAW_SUCCESS;
//                } else {
//                    $paymentNo = '';
//                    $withdrawalStatus = OauthCommission::WITHDRAW_FAIL;
//                }
//
//                // 更新提现信息
//                Db::name('oauth_commission')
//                ->where('id', $commissionId)
//                ->update([
//                    'payment_no' => $paymentNo,
//                    'withdrawal_status' => $withdrawalStatus,
//                    'withdrawal_time' => time()
//                ]);
//            }
//
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            dump($e->getMessage());exit;
            // 回滚事务
            Db::rollback();
            return false;
        }
    }
    
    public static   function debugLog($msg) {
        $fileName = "debug_" . date('Ymd', time()) . ".log";
        self::writeLog($msg, $fileName);
    }
    
    
    
    public static function writeLog($msg, $fileName) {
        $filePath = '/data/web/boxueteach.com/logs/';
        $file = $filePath . $fileName;
        if (!file_exists($filePath)) {
            mkdir($filePath, '0777', true);
        }
        if (is_writable(dirname($file))) {
            if (!is_string($msg)) {
                $msg = var_export($msg, TRUE);
            }
            file_put_contents($file, "#" . date('Y-m-d H:i:s') . $msg . "\r\n", FILE_APPEND);
        }
    }
    
    
}